package com.wrq.service.impl;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.wrq.pojo.OSSConstant;
import com.wrq.service.OssService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service("OssService")
public class OssServiceImpl implements OssService {
    @Override
    public void downFile( HttpServletResponse response ,String fileName,String oldFileName) {
        // oss文件地址


        // 获取域名后面的内容
        System.out.println("oss文件名字+"+fileName);
        // 获取oss文件byte[]
        byte[] oss_byte = getOssFileByteArray(fileName);
        // 后缀名
//        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        try {
            // 清空response
            response.reset();
//            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//             设置response的Header
            response.setHeader("Content-Disposition",
                    "attachment;filename=" +new String(oldFileName.getBytes("gb2312"), "ISO8859-1"));
//             response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

            toClient.write(oss_byte);// 以流的形式下载文件。
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    /**
     * 获取oss文件byte[]
     */
    public byte[] getOssFileByteArray(String filepath) {
        byte[] result = null;
        // 初始化配置参数
        String OSS_ENDPOINT = OSSConstant.OSS_ENDPOINT;
        String OSS_ACCESSKEYID = OSSConstant.OSS_ACCESSKEYID;
        String OSS_ACCESSKEYSECRET = OSSConstant.OSS_ACCESSKEYSECRET;
        String OSS_BUCKET = OSSConstant.OSS_BUCKET;
        OSSClient ossClient = null;
        try {
            if (filepath != null && !"".equals(filepath.trim())) {
                // 创建ClientConfiguration实例，按照您的需要修改默认参数
                ClientConfiguration conf = new ClientConfiguration();
                // 开启支持CNAME选项
                conf.setSupportCname(true);
                ossClient = new OSSClient(OSS_ENDPOINT, OSS_ACCESSKEYID, OSS_ACCESSKEYSECRET, conf);

                // 下载
                OSSObject ossObj = ossClient.getObject(OSS_BUCKET, filepath);
                if (ossObj != null) {
                    InputStream is = ossObj.getObjectContent();
                    result = InputStreamToByteArray(is);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件下载异常");
        } finally {
            // 关闭client
            ossClient.shutdown();
        }
        return result;
    }

    /**
     * 1.图片转为字节数组
     * 图片到程序FileInputStream
     * 程序到数组 ByteArrayOutputStream
     */
    public static byte[] InputStreamToByteArray(InputStream is) {
        // 1.创建源与目的的
        byte[] dest = null;// 在字节数组输出的时候是不需要源的。
        // 2.选择流，选择文件输入流
        ByteArrayOutputStream os = null;// 新增方法
        try {
            os = new ByteArrayOutputStream();
            // 3.操作,读文件
            byte[] flush = new byte[1024 * 10];// 10k，创建读取数据时的缓冲，每次读取的字节个数。
            int len = -1;// 接受长度；
            while ((len = is.read(flush)) != -1) {
                // 表示当还没有到文件的末尾时
                // 字符数组-->字符串，即是解码。
                os.write(flush, 0, len);// 将文件内容写出字节数组
            }
            os.flush();
            return os.toByteArray();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // 4.释放资源
            try {
                if (is != null) {// 表示当文打开时，才需要通知操作系统关闭
                    is.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        return null;

    }

}
